package com.yzc.android.manager.ibeacon;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import com.yzc.android.beans.BeaconBean;

/**
 * iBeacon扫描单例，可以开启或者关闭扫描
 *
 * @author frank
 *
 */
public class IBeaconScanManager {
	private static IBeaconScanManager instance = null;
	private static final String TAG = "IBeaconScanManager";

	public static final String PRE_KEY_IBEACON_UUID = "pre.key.ibeacon.uuid";
	public static final String PRE_KEY_IBEACON_MAJOR = "pre.key.ibeacon.major";
	public static final String PRE_KEY_IBEACON_MINOR = "pre.key.ibeacon.minor";
	public static final String PRE_KEY_IBEACON_IN_REGION = "pre.key.ibeacon.inregion";


	private Context context;
	private BluetoothAdapter bluetoothAdapter = null;

	private BeaconScanManagerListener mListener;

	private Handler mHandler = new Handler();

	private List<BeaconBean> mBeaconList = new ArrayList<>();

	//private boolean mScanning = false;

	/**
	 * 单例获取接口
	 *
	 * @return
	 */
	public synchronized static IBeaconScanManager getInstance() {
		if (instance == null) {
			instance = new IBeaconScanManager();
		}
		return instance;
	}

	/**
	 * 初始化接口
	 *
	 * @param context
	 * @return
	 */
	public boolean init(Context context) {
		boolean ret = false;
		synchronized (IBeaconScanManager.this) {
			this.context = context;
			if (isSuportBLE()) {
				final BluetoothManager bluetoothManager = (BluetoothManager) context
						.getSystemService(Context.BLUETOOTH_SERVICE);
				bluetoothAdapter = null;
				bluetoothAdapter = bluetoothManager.getAdapter();
				if (bluetoothAdapter != null) {
					ret = bluetoothAdapter.isEnabled();
				}
			}
		}
		return ret;
	}

	/**
	 * 判断是否支持BLE4.0及以上
	 *
	 * @return boolean 是否
	 */
	public boolean isSuportBLE() {
		boolean ret = false;
		try {
			ret = context.getPackageManager().hasSystemFeature(
					PackageManager.FEATURE_BLUETOOTH_LE);
		} catch (Exception e) {
			Log.e(TAG, "isSuportBeacon", e);
		}
		return ret;
	}

	/**
	 * 判断蓝牙是否打开
	 *
	 * @return boolean 是否
	 */
	public boolean isBluetoothEnabled() {
		boolean ret = false;
		if (bluetoothAdapter != null) {
			ret = bluetoothAdapter.isEnabled();
		}
		return ret;
	}

	/**
	 * 启动iBeacon扫描
	 */
	public void start() {
		if (isSuportBLE() && isBluetoothEnabled() && (bluetoothAdapter != null)) {
			bluetoothAdapter.startLeScan(leScanCallback);
			//mScanning = true;
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					//stop();
					//mScanning = false;
					if (mListener != null) {
						mListener.onBeaconScannedAndParsed(mBeaconList);
					}
					mBeaconList.clear();
				}
			}, 5*1000);
		}
	}

	//public boolean isScanning() {
	//	return mScanning;
	//}

	/**
	 * 停止iBeacon扫描
	 */
	public void stop() {
		if (isSuportBLE() && (bluetoothAdapter != null)) {
			try {
				bluetoothAdapter.stopLeScan(leScanCallback);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	public void setListener(BeaconScanManagerListener listener) {
		mListener = listener;
	}

	/**
	 * 关闭结束扫描类
	 */
	public void destory() {
		if (bluetoothAdapter != null) {
			bluetoothAdapter = null;
		}
	}

	private IBeaconScanManager() {

	}

	/**
	 * 扫描回调函数
	 */
	private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {

		@Override
		public synchronized void onLeScan(final BluetoothDevice device, final int rssi,
							 final byte[] scanRecord) {
			if (device != null) {
				BeaconBean beaconBean = BeaconBean.fromScanData(device, rssi, scanRecord);
				if (beaconBean == null) return;
				boolean found = false;
				for (BeaconBean beacon : mBeaconList) {
					if (beacon.proximityUuid.equals(beaconBean.proximityUuid) && beacon.major == beaconBean.major && beacon.minor == beaconBean.minor) {
						found = true;
						break;
					}
				}
				if (!found) {
					mBeaconList.add(beaconBean);
				}
			}
		}
	};

	public interface BeaconScanManagerListener {
		void onBeaconScannedAndParsed(List<BeaconBean> beaconList);
	}
}
